package com.woniuxy.gobang.ui;

import java.sql.Connection;

import dao.UserDataDAO;
import entity.User;
import gobang_util.DbUtil;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

/**
 * 登录页面
 * 
 * @author 张哲轩
 *
 */
public class LogOnStage extends Stage {
	private Label lbAccount = new Label("账号");
	private TextField txtAcount = new TextField();

	private Label lbPassword = new Label("密码");
	private PasswordField txtPassword = new PasswordField();
	private Stage stage = this;

	public LogOnStage() {
		// 为窗体设置标题
		setTitle("登录页面");
		// 设置窗体大小不可调整
		setResizable(false);
		// 创建面板
		Pane pane = new Pane();
		// 账号位置
		lbAccount.setLayoutX(30);
		lbAccount.setLayoutY(20);
		txtAcount.setLayoutX(100);
		txtAcount.setLayoutY(20);
		// 密码位置
		lbPassword.setLayoutX(30);
		lbPassword.setLayoutY(60);
		txtPassword.setLayoutX(100);
		txtPassword.setLayoutY(60);

		pane.getChildren().addAll(lbAccount, txtAcount, lbPassword, txtPassword);

		// 确认按钮
		Button confirmBtn = new Button("登录");
		confirmBtn.setPrefSize(100, 30);
		confirmBtn.setLayoutX(50);
		confirmBtn.setLayoutY(130);
		pane.getChildren().add(confirmBtn);
		// 确认按钮事件
		confirmBtn.setOnMouseClicked(new EventHandler<Event>() {
			@Override
			public void handle(Event event) {
				UserDataDAO userDAO = new UserDataDAO();
				try {
					Global.user = userDAO.getByAccountAndPwd(txtAcount.getText(), txtPassword.getText());
				} catch (Exception e) {
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setContentText("系统维护中");
					alert.show();
				}
				if (Global.user == null) {
					Alert alert = new Alert(AlertType.ERROR);
					alert.setContentText("账号或密码错误");
					alert.show();
				} else {
					stage.close();
					new SettingStage();
				}
			}
		});

		// 取消按钮
		Button cancelBtn = new Button("取消");
		cancelBtn.setPrefSize(100, 30);
		cancelBtn.setLayoutX(180);
		cancelBtn.setLayoutY(130);
		pane.getChildren().add(cancelBtn);
		// 取消按钮事件
		cancelBtn.setOnMouseClicked(new EventHandler<Event>() {
			@Override
			public void handle(Event event) {
				stage.close();
			}
		});

		Hyperlink link = new Hyperlink();
		link.setText("免费注册");
		link.setLayoutX(300);
		link.setLayoutY(130);
		pane.getChildren().add(link);
		link.setOnMouseClicked(new EventHandler<Event>() {
			@Override
			public void handle(Event event) {
				hide();
				new LogInStage();
				stage.close();
			}
		});

		// 创建一个场景对象
		Scene scene = new Scene(pane, 400, 180);
		// 将场景添加到窗体上
		setScene(scene);
		// 将线条添加到面板
		show();
	}
}
